package cj.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class HttpClientUtil
{
	public static void invokeHttpClient(String url) throws ClientProtocolException, IOException
	{
		// 创建HttpClient实例     
	    HttpClient httpclient = new DefaultHttpClient();  
	    // 创建Get方法实例     
	    HttpGet httpgets = new HttpGet(url);    
	    HttpResponse response = httpclient.execute(httpgets);    
	    HttpEntity entity = response.getEntity();    
	    if (entity != null) {    
	        InputStream instreams = entity.getContent();    
	        String str = convertStreamToString(instreams);  
	        System.out.println("Do something");   
	        System.out.println(str);  
	        // Do not need the rest    
	        httpgets.abort();    
	    }
	}
    
	private static String invoke(DefaultHttpClient httpclient,  
            HttpUriRequest httpost,String l_charset) {  
          
        HttpResponse response = sendRequest(httpclient, httpost);  
        String body = paseResponse(response,l_charset);  
          
        return body;  
    }  
	
	public static String post(String url, Map<String, String> params,String l_charset) {  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        String body = null;  
          
        HttpPost post = postForm(url, params);  
        
        body = invoke(httpclient, post, l_charset);  
        System.out.println(body);
        httpclient.getConnectionManager().shutdown();  
          
        return body;  
    }  
	
	private static String paseResponse(HttpResponse response,String l_charset) {  
        HttpEntity entity = response.getEntity();  
          
        String charset = EntityUtils.getContentCharSet(entity);  
          
        if(charset==null)
        {
        	charset =l_charset;
        }
        
        String body = null;  
        try {  
            body = EntityUtils.toString(entity,charset);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
        return body;  
    }  
  
    private static HttpResponse sendRequest(DefaultHttpClient httpclient,  
            HttpUriRequest httpost) {  
        HttpResponse response = null;  
          
        try {  
            response = httpclient.execute(httpost);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return response;  
    }  
  
    private static HttpPost postForm(String url, Map<String, String> params){  
          
        HttpPost httpost = new HttpPost(url);  
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
          
        Set<String> keySet = params.keySet();  
        for(String key : keySet) {  
            nvps.add(new BasicNameValuePair(key, params.get(key)));  
        }  
          
        try {  
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
          
        return httpost;  
    }  
      
    public static String get(String url,String l_charset) {  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        String body = null;  
          
        HttpGet get = new HttpGet(url);  
        body = invoke(httpclient, get,l_charset);  
          
        httpclient.getConnectionManager().shutdown();  
          
        return body;  
    }  
	
    private static String convertStreamToString(InputStream is) {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
               e.printStackTrace();      
            }      
        }      
        return sb.toString();      
    }  
    
    /**
     * 判断Url是否存在	通过Http协议判断通讯状态200为通过存在
     * @param urlStr
     * @return	true/false
     */
	public static boolean isConnect(String urlStr) {
		URL url;  
		HttpURLConnection con; 
		try {
			url = new URL(urlStr);
			con = (HttpURLConnection) url.openConnection();
			int state = con.getResponseCode();
			if (state == 200) {
				return true;
			}
		} catch (Exception ex) {
			return false;
		}
		return false;
	}
	
	/**
     * post请求
     *
     * @param url
     * @param jsonObject object
     * @return json object
     */
    public static String doPost(String url, JSONObject jsonObject) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
            StringEntity s = new StringEntity(jsonObject.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                result = EntityUtils.toString(entity);
                JSONObject jo = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
	
	public static void getParams() {
		 
	    // 获取连接客户端工具
	    CloseableHttpClient httpClient = HttpClients.createDefault();
	 
	    String entityStr = null;
	    CloseableHttpResponse response = null;
	 
	    try {
	        /*
	         * 由于GET请求的参数都是拼装在URL地址后方，所以我们要构建一个URL，带参数
	         */
	        URIBuilder uriBuilder = new URIBuilder("http://api.xzwjw.com/media/clues:search");
	        /** 第一种添加参数的形式 */
	        /*uriBuilder.addParameter("name", "root");
	        uriBuilder.addParameter("password", "123456");*/
	        /** 第二种添加参数的形式 */
	        List<NameValuePair> list = new LinkedList<>();
	        BasicNameValuePair param1 = new BasicNameValuePair("createTime", "");
	        BasicNameValuePair param2 = new BasicNameValuePair("listType", "3");
	        BasicNameValuePair param3 = new BasicNameValuePair("page", "");
	        BasicNameValuePair param4 = new BasicNameValuePair("size", "20");
	        list.add(param1);
	        list.add(param2);
	        uriBuilder.setParameters(list);
	 
	        // 根据带参数的URI对象构建GET请求对象
	        HttpGet httpGet = new HttpGet(uriBuilder.build());
	 
	        /* 
	         * 添加请求头信息
	         */
	        // 浏览器表示
	        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36");
	        // 传输的类型
	        httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
	        httpGet.addHeader("x-access-token", "e2fd401475c444d7ac9f47b768e54e5d");
	 
	        // 执行请求
	        response = httpClient.execute(httpGet);
	        // 获得响应的实体对象
	        HttpEntity entity = response.getEntity();
	        // 使用Apache提供的工具类进行转换成字符串
	        entityStr = EntityUtils.toString(entity, "UTF-8");
	    } catch (ClientProtocolException e) {
	        System.err.println("Http协议出现问题");
	        e.printStackTrace();
	    } catch (ParseException e) {
	        System.err.println("解析错误");
	        e.printStackTrace();
	    } catch (URISyntaxException e) {
	        System.err.println("URI解析异常");
	        e.printStackTrace();
	    } catch (IOException e) {
	        System.err.println("IO异常");
	        e.printStackTrace();
	    } finally {
	        // 释放连接
	        if (null != response) {
	            try {
	                response.close();
	                httpClient.close();
	            } catch (IOException e) {
	                System.err.println("释放连接出错");
	                e.printStackTrace();
	            }
	        }
	    }
	 
	    // 打印响应内容
	    System.out.println(entityStr);
	 
	}
    
    public static void main(String[] arga)
    {
//    	String url="http://mp.weixin.qq.com/s?__biz=MjM5ODU5NzQxNw==&mid=401252726&idx=1&sn=6cbdea92f9a6494a52f2e4573e3c9f8e&scene=4";
//    	String html=get(url, "utf-8");
//    	Document doc = Jsoup.parse(html, "UTF-8");
//    	Element classTable = doc.getElementsByTag("body").first();
//    	
//    	System.out.println(classTable.text());
    	
//    	getParams();
    	
    	JSONObject jo = new JSONObject();
    	jo.put("loginName", "cjrm");
    	jo.put("password", "cjrm123");
    	String result = doPost("http://api.xzwjw.com/u/login:pc", jo);
    	System.out.println(result);
    	
    	
    }
}
